package com.lecture.essence.demo03;

import com.lecture.essence.demo02.DowJonesNewsListener;
import com.lecture.essence.demo02.DowJonesNewsPersister;
import com.lecture.essence.demo02.FXNewsProvider;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;

public class Demo03 {
    public static void main(String[] args) {
        DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();
        BeanFactory beanFactory = bindViaCode(beanRegistry);
        FXNewsProvider newsProvider = (FXNewsProvider)beanFactory.getBean("newsProvider");
        newsProvider.getAndPersistNews();

    }

    public static BeanFactory bindViaCode(BeanDefinitionRegistry registry) {
        AbstractBeanDefinition newsProvider = new RootBeanDefinition(FXNewsProvider.class);
        AbstractBeanDefinition newsListener = new RootBeanDefinition(DowJonesNewsListener.class);
        AbstractBeanDefinition newsPersiter = new RootBeanDefinition(DowJonesNewsPersister.class);

        //将bean定义注册到容器中
        registry.registerBeanDefinition("newsProvider",newsProvider);
        registry.registerBeanDefinition("newsListener",newsListener);
        registry.registerBeanDefinition("newsPersiter",newsPersiter);

        //指定依赖关系
        //1：通过构造方法注入方式
        ConstructorArgumentValues argumentValues = new ConstructorArgumentValues();
        argumentValues.addIndexedArgumentValue(0,newsListener);
        argumentValues.addIndexedArgumentValue(1,newsPersiter);
        newsProvider.setConstructorArgumentValues(argumentValues);

        //2：通过setter方法注入
        /*MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.addPropertyValue(new PropertyValue("newsListener",newsListener));
        propertyValues.addPropertyValue(new PropertyValue("newsPersiter",newsPersiter));
        newsProvider.setPropertyValues(propertyValues);*/
        return (BeanFactory) registry;
    }
}
